<template>
	<!-- 城市选择-->
	<view class="city-select">
		<view style="padding: 0 28rpx;">
			<view class="title">选择城市</view>
			<!-- 当前定位城市 -->
			<view class="now-city" v-if="!searchText">
				<text>当前城市：</text>
				<uni-icons type="refreshempty" size="20" v-if="!location.cityName" @click="getLocationCity"></uni-icons>
				<text v-else @click="cityTrigger(location)">{{ location.cityName }}</text>
			</view>

			<!-- 预留搜索-->
			<view class="city-serach">
				<icon type="search" size="18" style="position: absolute;left: 24rpx;top: 50rpx;"></icon>
				<input v-model="searchText" :placeholder="placeholder" class="city-serach-input" />
			</view>
			<!-- 热门城市 -->
			<view v-if="hotCity.length > 0 && !searchText">
				<view class="hot-title" style="line-height: 36rpx;">热门城市</view>
				<view class="hot-city">
					<view v-for="(item, index) in hotCity" :key="index" @click="cityTrigger(item, 'hot')" class="hot-item">{{ item[formatName] }}</view>
				</view>
			</view>
		</view>
		<!-- 城市列表(搜索后)  -->
		<view class="citys" v-if="searchText">
			<view v-for="(item, index) in searchDatas" :key="index" class="citys-row">
				<view class="citys-item" :key="index" @click="cityTrigger(item)">{{ item.name }}</view>
			</view>
		</view>
		<!-- 城市列表(搜索前) -->
		<scroll-view v-else :scroll-top="scrollTop" scroll-y="true" class="city-select-main" id="city-select-main" :scroll-into-view="toView">
			<view class="citys">
				<view v-for="(city, index) in sortItems" :key="index" v-show="city.isCity" class="citys-row">
					<view class="citys-item-letter" :id="'city-letter-' + (city.name === '#' ? '0' : city.name)">{{ city.name }}</view>
					<view class="citys-item" v-for="(item, inx) in city.citys" :key="inx" @click="cityTrigger(item)">{{ item.cityName }}</view>
				</view>
			</view>
		</scroll-view>
		<!-- 城市选择索引-->
		<view class="city-indexs-view" v-if="!searchText">
			<view class="city-indexs">
				<view v-for="(cityIns, index) in handleCity" class="city-indexs-text" v-show="cityIns.isCity" :key="index" @click="cityindex(cityIns.forName)">
					{{ cityIns.name }}
				</view>
			</view>
		</view>
		<view class="cont_Letter" v-if="isShowLetter">{{ showLetter }}</view>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import http from '@/common/request.js';
import citySelect from './citySelect.js';
import {authorTodo} from '@/common/utils.js'
export default {
	props: {
		//查询提示文字
		placeholder: {
			type: String,
			default: '请输入城市名称'
		},
		//传入要排序的名称
		formatName: {
			type: String,
			default: 'cityName'
		},
		//热门城市
		hotCity: {
			type: Array,
			default: () => []
		},
		//城市数据
		obtainCitys: {
			type: Array,
			default: () => []
		},
		//是否有搜索
		isSearch: {
			type: Boolean,
			default: true
		}
	},
	onLoad() {
		uni.setBackgroundColor({
			backgroundColor: '#ffffff'
		});
	},
	data() {
		return {
			location: {},
			isShowLetter: false,
			showLetter: '',
			toView: 'city-letter-Find', //锚链接 初始值
			scrollTop: 0, //scroll-view 滑动的距离
			cityindexs: [], // 城市索引
			activeCityIndex: '', // 当前所在的城市索引
			handleCity: [], // 处理后的城市数据
			searchText: '', // 搜索的城市
			cityData: [],
			isSearching: false
		};
	},
	computed: {
		/**
		 * @desc 城市列表排序
		 * @return  Array
		 */
		sortItems() {
			for (let index = 0; index < this.handleCity.length; index++) {
				if (this.handleCity[index].isCity) {
					let cityArr = this.handleCity[index].citys;
					cityArr = cityArr.sort(function(a, b) {
						var value1 = a.unicode;
						var value2 = b.unicode;
						return value1 - value2;
					});
				}
			}
			return this.handleCity;
		},
		/**
		 * @desc 搜索后的城市列表
		 * @return Array
		 */
		searchDatas() {
			var searchData = [];
			for (let i = 0; i < this.cityData.length; i++) {
				if (this.cityData[i][this.formatName].indexOf(this.searchText) !== -1) {
					searchData.push({
						oldData: this.cityData[i],
						name: this.cityData[i][this.formatName]
					});
				}
			}
			return searchData;
		}
	},
	created() {
		// 初始化城市数据
		this.cityData = this.obtainCitys;
		this.initializationCity();
		this.buildCityindexs();
	},
	watch: {
		obtainCitys(newData) {
			this.updateCitys(newData);
		}
	},
	mounted() {
		this.getLocationCity();
	},
	methods: {
		getLocationCity() {
			// #ifdef MP-WEIXIN
			authorTodo({
				type: 'userLocation',
				success: () => {
			// #endif
					uni.getLocation({
						type: 'gcj02',
						success: res => {
							this.$store.dispatch('getLocationByGPS', res).then(location => {
								this.location = location;
							});
						}
					});
			// #ifdef MP-WEIXIN
				}
			})
			// #endif
		},
		/**
		 * @desc 初始化
		 */
		updateCitys(data) {
			if (data && data.length) {
				this.cityData = data;
				this.initializationCity();
				this.buildCityindexs();
			}
		},
		/**
		 * @desc 监听输入框的值
		 */
		keyInput(e) {
			e.target.focus();
		},
		/**
		 * @desc 初始化城市数据
		 * @return undefind
		 */
		initializationCity() {
			this.handleCity = [];
			const cityLetterArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'];
			for (let index = 0; index < cityLetterArr.length; index++) {
				this.handleCity.push({
					name: cityLetterArr[index],
					isCity: false, // 用于区分是否含有当前字母开头的城市
					citys: [], // 存放城市首字母含是此字母的数组
					forName: 'city-letter-' + (cityLetterArr[index] == '#' ? '0' : cityLetterArr[index]) //label的绑定
				});
			}
		},
		/**
		 * @desc 得到城市的首字母
		 * @param str String
		 */
		getLetter(str) {
			return citySelect.getFirstLetter(str[0]);
		},
		/**
		 * @desc 构建城市索引
		 * @return undefind
		 */
		buildCityindexs() {
			this.cityindexs = [];
			for (let i = 0; i < this.cityData.length; i++) {
				// 获取首字母
				const cityLetter = this.getLetter(this.cityData[i][this.formatName]).firstletter;
				// 获取当前城市首字母的unicode，用作后续排序
				const unicode = this.getLetter(this.cityData[i][this.formatName]).unicode;

				const index = this.cityIndexPosition(cityLetter);
				if (this.cityindexs.indexOf(cityLetter) === -1) {
					this.handleCity[index].isCity = true;
					this.cityindexs.push(cityLetter);
				}

				this.handleCity[index].citys.push({
					cityName: this.cityData[i][this.formatName],
					unicode: unicode,
					oldData: this.cityData[i]
				});
			}
		},

		/**
		 * @desc 滑动到城市索引所在的地方
		 * @param id String 城市索引
		 */
		cityindex(id) {
			this.isShowLetter = true;
			this.toView = id;
			this.showLetter = id.split('-')[2];
			setTimeout(() => {
				this.isShowLetter = false;
			}, 1000);
		},
		/**
		 * @desc 获取城市首字母的unicode
		 * @param letter String 城市索引
		 */
		cityIndexPosition(letter) {
			if (!letter) {
				return '';
			}
			const ACode = 65;
			return letter === '#' ? 26 : letter.charCodeAt(0) - ACode;
		},
		/** @desc 城市列表点击事件
		 *  @param Object
		 */
		cityTrigger(item) {
			// 传值到父组件
			this.$emit('cityClick', item.oldData ? item.oldData : item);
			uni.navigateTo({
				url: '../../pages/home/index',
				animationType: 'pop-in',
				animationDuration: 200
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.title {
	font-size: 48rpx;
	color: #4a4943;
	line-height: 67rpx;
	font-weight: 600;
	padding: 25rpx 0;
	background: #fff;
}

//宽度转换vw
@function vww($number) {
	// @return ($number / 375) * 750 + rpx;
	@return ($number * 2) + rpx;
}

view {
	box-sizing: border-box;
}

.now-city {
	margin-top: 36rpx;
	font-size: 30rpx;
	font-weight: 400;
	color: #4a4943;
	line-height: 42rpx;
	display: flex;
	align-items: center;
}
.city-serach {
	display: flex;
	background: #fff;
	position: relative;
	padding-top: 36rpx;
	&-input {
		width: 100%;
		padding-left: 68rpx;
		background: #f7f7f7;
		color: #8a8c8d;
		font-size: 26rpx;
		border-radius: 30rpx;
		height: 60rpx;
	}
}

.city-select-main {
	position: fixed;
	width: 100%;
	top: 568rpx;
	height: calc(100% - 568rpx);
}

.city-location {
	background-color: #fff;
	font-size: vww(14);
	padding: vww(12) vww(18);
	color: #ff9524;
	display: flex;
	align-items: center;
}

.city-select {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #fff;
	// 热门城市
	.hot-title {
		padding-top: 24rpx;
		width: 100vw;
		font-size: 14px;
		line-height: vww(40);
		color: #9b9b9b;
		background: #fff;
	}
	.hot-city {
		overflow: hidden;
		background: #fff;
		color: #999999;
		display: flex;
		flex-wrap: wrap;
		margin: 25rpx 0 16rpx 0;
		.hot-item {
			margin: 11rpx;
			width: calc((100% - 66rpx) / 4);
			height: 72rpx;
			line-height: 72rpx;
			text-align: center;
			font-size: 26rpx;
			border-radius: 12rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
			overflow: hidden;
			color: #66645d;
			background: #fff;
			border: 1px solid rgba(102, 100, 93, 0.5);
			&:nth-child(4n-3) {
				margin-left: 0;
			}
			&:nth-child(4n + 4) {
				margin-right: 0;
			}
		}

		.hot-hidden {
			display: none;
			margin-right: 0;
		}
	}

	.citys {
		.citys-row {
			width: 100%;
			font-size: 14px;
			.citys-item-letter {
				padding-left: vww(18);
				margin-top: -1px;
				width: 100vw;
				line-height: vww(30);
				color: #9b9b9b;
				background: #fff;
				border-top: none;
			}

			.citys-item {
				padding-left: vww(18);
				width: 100%;
				line-height: vww(48);
				color: #4a4a4a;
				background: #fff;
				position: relative;

				&:after {
					content: '';
					position: absolute;
					left: vww(18);
					right: 0;
					bottom: 0;
					height: vww(1);
					background-color: #eee;
					transform: scaleY(0.5);
				}

				&:last-child {
					&:after {
						height: 0;
					}
				}
			}
		}
	}

	.cont_Letter {
		background-color: #666;
		color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		position: fixed;
		top: 50%;
		left: 50%;
		margin: -50px;
		width: 100px;
		height: 100px;
		border-radius: 10px;
		font-size: 26px;
		z-index: 1;
	}

	.city-indexs-view {
		position: fixed;
		right: 0;
		top: 568rpx;
		bottom: 0;
		z-index: 999;
		display: flex;
		width: vww(20);
		text-align: center;

		.city-indexs {
			width: vww(20);
			text-align: center;
			vertical-align: middle;
			align-self: center;

			.city-indexs-text {
				margin-bottom: 8rpx;
				width: vww(20);
				font-size: 22rpx;
				color: #999999;

				&:last-child {
					margin-bottom: 0;
				}
			}
		}
	}
}
</style>
